##################################################################
##
##
##  timer.tcl script to interface with Synopsys PrimeTime
##
##  This code is provided for description purposes only. The contest
##  organizers cannot guarantee that the provided code is free of
##  bugs or defects. !!!! USE THIS CODE AT YOUR OWN RISK !!!!!
##
##
##  The contestants are free to use these functions as-is or make
##  modifications. If the contestants choose to use the provided
##  code, they are responsible for making sure that it works as
##  expected. We will not be accepting timer.tcl from contestants, we
##  will use our own version for evaluation purposes (which we released
##  to you).
##
##  The code provided here has no real or implied warranties.
##
##
####################################################################

# Check command line
if { $argc != 1 } {
    puts "$argv0 <Synopsys-PrimeTime-Executable>"
    exit 1
}

# Perform checks on required environment variable
if { [catch {set contest_root $::env(ISPD_CONTEST_ROOT)} ] } {
    puts "Error: Please define environment variable ISPD_CONTEST_ROOT and re-run timer.tcl"
    exit 1
}

# Perform checks on required environment variable
if { [catch {set design_name $::env(ISPD_CONTEST_BENCHMARK)} ] } {
    puts "Error: Please define environment variable ISPD_CONTEST_BENCHMARK and re-run timer.tcl"
    exit 1
}

# Get name of Synopsys PrimeTime* executable from command line
set ptexe [lindex $argv 0]
puts "Timer: Synopsys PrimeTime executable is '$ptexe'"

# Run Synopsys PrimeTime and keep restarting it if it fails
# Following uses pt_scripts.tcl so ensure that it exists in
# the same directory. Ensure that you have write permissions
# in the same directory.
puts "-I- Timer: Starting Synopsys PrimeTime"
file delete -force "__PT_STARTUP_ERROR_"
file delete -force pt.log
set i 1
while { 1 } {
    catch { exec $ptexe -f pt_scripts.tcl >>& pt.log }
    if { [file exists "$contest_root/$design_name/__TCMD_SHUTDOWN_"] } {
        puts "-I- Timer: Exiting timer"
        file delete -force "$design_name/__TCMD_SHUTDOWN_"
        break
    }
    if { [file exists "__PT_STARTUP_ERROR_"] } {
        puts "-E- Timer: Could not start up timer properly"
        file delete -force "__PT_STARTUP_ERROR_"
        break
    }
    puts "-W- Timer: Synopsys PrimeTime quit prematurely, restarting it (restart number $i)"
    incr i
}

exit 0
